﻿using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using Microsoft.WindowsAzure.StorageClient;

namespace FLH.RegionToBlockUogIDs
{
	/// <summary>
	/// LookUpsSource maps to the Azure tables and provides the CRUD methods.
	/// </summary>
	public class RegionToBlockUogIDsSource
	{
		private readonly RegionToBlockUogIDsServiceContext _projectDataServiceContext;

		/// <summary>
		/// Constructs the datasource. Always checks to see if the table has
		/// previously been created. If not then it creates the table 
		/// using the data context. (NOT recommended for production code.)
		/// </summary>
		public RegionToBlockUogIDsSource()
		{
			var storageAccount = AzureTableInitialization.GetAccount();
			_projectDataServiceContext = new RegionToBlockUogIDsServiceContext(storageAccount.TableEndpoint.ToString(),
																				   storageAccount.Credentials);
			//Fixed in Azure				//{
			//    // Optimization: Where table name and class name are not the same
			//    // ResolveEntityType is the name of the method that supplies the object type
			//    // To improve performance of ADO.NET Data Service deserialization 
			//    ResolveType = (unused) => typeof(LookUpsModel)
			//};

		}


		#region READ methods (by Partition, by Partition/Row) http://msdn.microsoft.com/en-us/library/dd894039.aspx

		/// <summary>
		/// Read (select) all rows in the specified partition from the client table.
		/// </summary>
		/// <param name="prefix">The prefix.</param>
		/// <param name="regionID">The region ID.</param>
		/// <returns></returns>
		public IEnumerable<RegionToBlockUogIDsModel> Read(string prefix, int regionID)
		{
			if (String.IsNullOrEmpty(prefix)) return null;
			var partitionKey = prefix + "__" + regionID;

			if (String.IsNullOrEmpty(partitionKey)) return null;
			_projectDataServiceContext.MergeOption = MergeOption.NoTracking;	// set when you will not be updating this entity
			IQueryable<RegionToBlockUogIDsModel> results;
			try
			{
				results = from c in _projectDataServiceContext.LookUpsTable
						  where c.PartitionKey == partitionKey
						  select c;
			}
			catch (Exception)
			{
				return null;
			}

			try
			{
				var query = results.AsTableServiceQuery();
				var queryResults = query.Execute();
				return queryResults.ToList();
			}
			catch (Exception)
			{
				return null;
			}
		}

		#endregion

	}
}


